import React, { useEffect, useState } from 'react';
import { Modal, message, Form, Input } from 'antd';
import Editor from '../Editor';
import FileUpload from '../FileUpload';
import { handleFileUrl, handleFileid } from '@/utils/utils';
import { savePublicity, updatePublicity } from '@/services/public'

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

interface MaterialsProps {
  visible: boolean;
  info?: any;
  onCancel: () => void;
  onSubmit: () => void;
}

const Materials: React.FC<MaterialsProps> = ({
  visible,
  info,
  onCancel,
  onSubmit,
}) => {
  const [form] = Form.useForm();
  const [imgList, setImg] = useState<any[]>([]);

  const handleOkSubmit = async () => {
    const fieldsValue: any = await form.validateFields();
    const par: any = {
      title: fieldsValue.title,
      type: 5,
    };
    if (fieldsValue.attachment) {
      par.attachment = handleFileid(fieldsValue.attachment);
    }
    const res = await savePublicity(par);
    if (res.success) {
      message.success('上传成功');
      onSubmit();
    } else {
      message.error(res.errMsg || '保存失败');
    }
  };

  // useEffect(() => {
  //   if (info) {
  //     if (info.attachment && info.attachmentUrl) {
  //       const imgs = handleFileUrl(info.attachment, info.attachmentUrl);
  //       setImg(imgs)
  //     }
  //   }
  // }, [info])

  return (
    <Modal
      title={'资料上传'}
      maskClosable={false}
      onCancel={onCancel}
      visible={visible}
      width={600}
      okText="确认"
      cancelText="取消"
      onOk={handleOkSubmit}
    >
      <Form {...formItemLayout} name="save_project" form={form}>
        <FormItem
          label="资料名称"
          name="title"
          initialValue={''}
          rules={[{ required: true, message: '请输入资料名称！' }]}
        >
          <Input placeholder="请输入标题,可先上传文件自动读取" />
        </FormItem>
        <FormItem
          label="资料文件"
          name="attachment"
          initialValue={[]}
          rules={[{ required: true, message: '请上传资料文件！' }]}
        >
          <FileUpload
            ossEnum="PROJECT"
            multiple={true}
            max={6}
            type="image/*,.pdf,.doc,.docx,.zip,.rar"
            onChange={(file) => {
              const name = form.getFieldValue('title');
              if (!name) {
                if (file && file.length == 1) {
                  const fileOne = file[0];
                  form.setFieldsValue({ title: fileOne.name })
                }
              }
            }}
          />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default Materials;
